﻿using Dapper;
using Npgsql;
using Oracle.ManagedDataAccess.Client;
using PLM.ConfigurationCenter.Core.Expansion;
using PLM.ConfigurationCenter.Model;
using PLM.ConfigurationCenter.SqlSugar;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;

namespace PLM.ConfigurationCenter.Handler {
    public class CommonServerHelper {


        /// <summary>
        /// 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string GetDBConn(DatabaseInfoModel model) {
            string str;
            if (model.DBType == 1) {
                str = $"Data Source={model.IPAddress};Initial Catalog={model.DbName};User ID={model.UserName};Password={model.Password};";
            } else if (model.DBType == 3) {
                str = $"PORT={model.Port};DATABASE={model.DbName};HOST={model.IPAddress};PASSWORD={model.Password};USER ID={model.UserName};";
            } else {
                str = $"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={model.IPAddress})(PORT={model.Port}))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME={model.ServerName})));User Id={model.UserName};Password={model.Password};";
            }
            return str;
        }
        /// <summary>
        /// 检查数据库连接
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public string CheckHealth(int dbtype, string dbconn) {
            string message = "";
            try {
                if (dbtype == 1) {
                    string sql = " select '数据库连接成功' ";
                    using (var dbcontext = new SqlConnection(dbconn)) {
                        dbcontext.QueryFirst<string>(sql);
                    }
                } else if (dbtype == 2) {
                    string sql = " select '数据库连接成功' from dual ";
                    using (var dbcontext = new OracleConnection(dbconn)) {
                        dbcontext.QueryFirst<string>(sql);
                    }
                } else {
                    string sql = " select '数据库连接成功' ";
                    using (var dbcontext = new NpgsqlConnection(dbconn)) {
                        dbcontext.QueryFirst<string>(sql);
                    }
                }
            } catch (Exception ex) {
                message = ex.Message;
            }
            return message;
        }
        /// <summary>
        /// 检查Pg数据库
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static bool CheckPgDatabaseHealth(out string message) {
            message = "";
            var dbModel = DbManager.DbContext.Queryable<DatabaseInfoModel>().First(p => p.Id == "AuxiliaryDb");
            if (dbModel == null) {
                message = "未设置PostgreSQL数据库";
                return false;
            }
            try {
                var dbconn = GetDBConn(dbModel);
                string sql = " select '数据库连接成功' ";
                using var dbcontext = new NpgsqlConnection(dbconn);
                dbcontext.QueryFirst<string>(sql);
            } catch (Exception ex) {
                message = ex.Message;
                return false;
            }
            return true;
        }
        /// <summary>
        /// 检查Pg数据库
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static bool CheckPgDatabaseHealth(string dbconn, out string message) {
            message = "";
            if (dbconn.IsEmpty()) {
                message = "未设置PostgreSQL数据库";
                return false;
            }
            try {
                string sql = " select '数据库连接成功' ";
                using var dbcontext = new NpgsqlConnection(dbconn);
                dbcontext.QueryFirst<string>(sql);
            } catch (Exception ex) {
                message = ex.Message;
                return false;
            }
            return true;
        }
        #region 文件
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name=""></param>
        public static void WriteFile(string filePath, List<string> strList) {
            //创建StreamWriter 类的实例
            StreamWriter streamWriter = new StreamWriter(filePath);
            //向文件中写入内容
            foreach (string str in strList) {
                streamWriter.WriteLine(str);
            }
            //刷新缓存
            streamWriter.Flush();
            //关闭流
            streamWriter.Close();
        }
        /// 
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name=""></param>
        public static void WriteFile(string filePath, string content) {
            //创建StreamWriter 类的实例
            StreamWriter streamWriter = new StreamWriter(filePath);
            //向文件中写入内容
            streamWriter.WriteLine(content);
            //刷新缓存
            streamWriter.Flush();
            //关闭流
            streamWriter.Close();
        }
        #endregion


        #region 时间转换

        /// <summary>
        /// 秒转时间
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string TimeFormat(int time) {
            var ts = new TimeSpan(0, 0, time);
            return $"{ts.Days}天{ts.Hours}小时{ts.Minutes}分钟{ts.Seconds}秒";
        }

        /// <summary>
        /// 时间差值获取秒数
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public static int TimeSpan(DateTime startTime, DateTime endTime) {
            var ts = endTime.Subtract(startTime);
            var sec = (int)ts.TotalSeconds;
            return sec;
        }

        #endregion


    }
}
